import app from '../main'
import { session } from 'js/util'

const request = (method, url, data = {}, async=true) => {
  if (!/chat\/sendMessage/.test(url) && async) {
    app.$spin.show()
  }
  return new Promise((resolve, reject) => {
    $.ajax({
      type: method,
      url: url,
      async: async,
      timeout : 10000,
      data: JSON.stringify(data),
      contentType:'application/json',
      success(result) {
        if (!/chat\/sendMessage/.test(url)) {
          app.$spin.hide()
        }
        const path = app.$route.path
        const code = result.code
        if (path == '/register' || path == '/login' || path == '/forget') {
          resolve(result)
          return
        }
        // 如果是首页上的登陆
        if (url.indexOf('/login') > 0) {
          resolve(result)
          return
        }
        if (code == '200' || code == '2000') { //请求成功
          resolve(result.data)
        } else if (code == '400' || code == '2001') {
          resolve(result.code)
          // app.$toast(result.msg)
        } else if (code == '8000' || code == '4011') {
          resolve(result.code)
          app.$toast(result.msg)
        } else if (code == '1005' || code == '1006' || code == '1007' || code == '1009') { // 当前未登录
          app.$toast('用户登录信息失效，请重新登录', () => {
            session.remove('userInfo')
            app.$router.push(`/login?redirect=${encodeURIComponent(app.$route.fullPath)}`)
          })
        } else { // 请求失败
          app.$toast(result.msg)
        }
      },
      error(err) {
        app.$spin.hide()
      }
    })
  })
}

export default {
  get(url, data, async) {
    return request('get', url, data, async)
  },
  post(url, data, async) {
    return request('post', url, data, async)
  }
}